<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use Auth, Redirect;

class Authenticate {

	/**
	 * The Guard implementation.
	 *
	 * @var Guard
	 */
	protected $auth;

	/**
	 * Create a new filter instance.
	 *
	 * @param  Guard  $auth
	 * @return void
	 */
	public function __construct(Guard $auth){
		$this->auth = $auth;
	}

	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next){
		//验证
		if(Auth::guest()){//来宾（未登录用户）
            return $this->error($request);
		}else{//登录用户
            $loginUser = Auth::user();
            //检查用户状态
            if($loginUser->status != '1'){
                return $this->error($request);
            }
		}
		return $next($request);
	}
    
    private function error($request){
        if($request->ajax()){
            exit(json_encode([
                'status' => '-1',
                'msg' => '未登录'
            ], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
        }else{
            return Redirect::to('/login');
        }
    }
}
